/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package org.cursoexperto.jftf.jsf.pack;

import java.math.BigDecimal;
import javax.faces.application.FacesMessage;
import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.convert.Converter;
import javax.faces.convert.ConverterException;

/**
 *
 * @author Jose Fernando
 */
public class BigDecimalConverter implements Converter {

    public Object getAsObject(FacesContext facesContext, UIComponent uiComponent, String string) {
        try {
            if (string == null || string.equals("")) {
                return null;
            }
            string = string.replace(",", ".");
            return new BigDecimal(string);
        } catch (Exception e) {
            FacesMessage facesMessage = new FacesMessage();
            facesMessage.setDetail("El valor no es un número válido");
            facesMessage.setSummary("El valor no es un número válido");
            facesMessage.setSeverity(FacesMessage.SEVERITY_ERROR);
            throw new ConverterException(facesMessage);
        }
    }

    public String getAsString(FacesContext facesContext, UIComponent uiComponent, Object object) {
        try {
            if (object != null) {
                return object.toString().replace(".", ",");
            } else {
                return null;
            }
        } catch (Exception e) {
            throw new ConverterException(e);
        }
    }
}
